import java.util.Random;
import java.util.Timer;
import java.util.TimerTask;

import org.eclipse.swt.SWT;
import org.eclipse.swt.events.PaintEvent;
import org.eclipse.swt.events.PaintListener;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Canvas;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Shell;

public class GUI2 {
private static int x=0,y=0;

	// a thread that updates the x,y vars randomly  
	private static class MyThreead extends Thread{
	 Random r=new Random();
	 public void run(){
	  while (true){
	   x=r.nextInt(500);
	   y=r.nextInt(500);
	   try {Thread.sleep(100);} catch (InterruptedException e) {}    
	  }
	 }
	}

	private static class RedrawTask extends TimerTask{
	 Canvas c;
	 Display d;
	 
	 public void setCanvas(Canvas c){
	  this.c=c;
	  d=c.getDisplay();
	 }
	 @Override
	 public void run() {  
	System.out.println("hellp");
		 d.asyncExec(new Runnable(){
			 public void run() {
				 if(!c.isDisposed()){
					 c.redraw();
					 c.update();
				 }
			 }
		 });
	 }
	}
	// a PaintListener
	private static class MyPaintListener implements PaintListener{
	 public void paintControl(PaintEvent e) {
System.out.println("in mypaintlist");
	  e.gc.drawOval(x-10, y-10, 20,20); // draw the circle around x,y
	 }
	}

public static void main(String[] args) {
    Display display = new Display();
    final Shell shell = new Shell(display);
    shell.setLayout(new GridLayout(1,true));
    shell.setSize(500,500);
    Button b=new Button(shell,SWT.PUSH);
    b.setText("hello");
    b.setLayoutData(new GridData(SWT.FILL,SWT.NONE,true,false));
    Canvas c=new Canvas(shell,SWT.NONE);
    c.setLayoutData(new GridData(SWT.FILL,SWT.FILL,true,true));
    MyPaintListener pl=new MyPaintListener();
    c.addPaintListener(pl);

    Thread t=new MyThreead(); // the thread that updates x,y randomly
    t.start();
   
    RedrawTask rt=new RedrawTask();
    rt.setCanvas(c);
    Timer ti=new Timer();
    ti.scheduleAtFixedRate(rt, 0, 1000);
   

   
    shell.open();    
    while (!shell.isDisposed()) {
      if (!display.readAndDispatch()) {        
        display.sleep();
      }
    }
    rt.cancel();
    ti.cancel();
    display.dispose();
}
}